<script setup>
import { reactive, ref, onMounted,} from 'vue';
import { ElMessage } from 'element-plus';
import MapSelector from '../common/MapSelector.vue';
import { orderTypeMap, statusMap } from '@/utils/dict';
// import { useRouter } from 'vue-router';
import { queryPageList, updateWorkorder,deleteOrder,assignWorkorder,getEmployee,getOrderDetail,updateStatus } from '@/apis/workorderAPI';

// const router=useRouter();
const workorderList = ref([]);
const isEditDialogOpen = ref(false);
const currentWorkorder = reactive({
  id:'',
  title:'',
  des:'',
  name:'',
  phone:'',
  address:'',
  status:''
});
const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);         // 每页条数，

//  编辑功能
const openDialog = (row) => {
  // 使用 JSON.parse(JSON.stringify()) 进行深拷贝，确保所有数据都被复制
  const workorderCopy = JSON.parse(JSON.stringify(row));

  // 清空 currentWorkorder
  Object.keys(currentWorkorder).forEach(key => {
    currentWorkorder[key] = '';
  });

  // 将拷贝后的数据赋值给 currentWorkorder
  Object.assign(currentWorkorder, workorderCopy);

  // 打开对话框
  isEditDialogOpen.value = true;
};
const loading = ref(true);
//  保存编辑
const saveWorkorder =async () => {
  try{
    console.log("完整的编辑数据",currentWorkorder);
    const response=await updateWorkorder(currentWorkorder);
    console.log("后端返回的信息",response);
    ElMessage.success("编辑成功");
    fetchData();
  }catch{
    ElMessage.error("编辑失败");
  }finally{
    isEditDialogOpen.value=false;
  }

};
  const params = reactive({
      pageNo:'', // 从1开始
      pageSize: '',
      startDate:'',
      status:''
    });
// 6. 删除功能
const deleteWorkorder = async(workorder) => {
  const deleteId = workorder.id;
  try {
    await deleteOrder(deleteId);
    // 后端删除成功后，删除本地列表中的对应数据
    const index = workorderList.value.findIndex(item => item.id === deleteId);
    fetchData();
    if (index !== -1) {
     workorderList.value.splice(index, 1);
    }
    ElMessage.success('删除成功');
    fetchData();
  } catch {
    ElMessage.error("删除失败");
  }
};
// 计算属性：显示给用户的页码（+1）
// const addWorkorder=()=>{}
//跳转详情页
// const toDetail=(row)=>{
//    router.push({
//     path: `/orderDetail/${row.id}`,
//   });
// };
 const total=ref(0);
onMounted(async () => {
  await fetchData();
});
const fetchData = async () => {
  try {
    loading.value = true;
    params.pageNo = currentPage.value;
    params.pageSize = pageSize.value;
    const { data } = await queryPageList(params);
    const { records } = data;

    workorderList.value = records;
    total.value = data.total;
    console.log('返回的数据:', data);
    console.log('records:', records);
    console.log('workorderList:', workorderList.value);

  } catch (error) {
    console.error('错误:', error);
    ElMessage.error("加载失败");
  } finally {
    loading.value = false;
  }
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData(); // 重新请求
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData(); // 重新请求
};
const handleSearch=()=>{
  params.pageNo=1;
   console.log("搜索参数:", params);
  fetchData();
};
const delivererList = ref([]);
const assignDialog=ref(false);
const fetchDelData=async()=>{
  try{
    const {data}=await getEmployee();
    console.log("后端返回的数据",data);
    delivererList.value=data;
  }catch{
    ElMessage.error("接单员加载失败");
  }
}
const orderId=ref();
const assignDialogOpen=(id)=>{
  orderId.value=id;
  fetchDelData();
  assignDialog.value=true;
}
// const userStore=useUserStore();
const handleAssign=async(deliverer)=>{
  try{

    const employeeId=deliverer.id;
    // console.log("token值",userStore.token)
    const response= await assignWorkorder(orderId.value,employeeId);
    console.log("分配接单员后端返回的数据",response);
    ElMessage.success("分配成功");
  }catch{
    ElMessage.error("分配失败");
  }finally{
    assignDialog.value=false;
    fetchData();
  }
}
const archivedId=ref();
const archivedStatus=ref();
const archived=async(workorder)=>{
  archivedId.value=workorder.id;
  archivedStatus.value=5;
  await updateStatus(archivedId.value,archivedStatus.value);
  fetchData();

}

const  currentId=ref();
// 打开弹窗的方法
const dialogVisible=ref(false);
const isOpenDialog = (id) => {
  currentId.value=id;
  fetchDetail();
  dialogVisible.value=true;

};
const detailData=ref({});
const feedback=ref({});
const fetchDetail=async()=>{
  try{
    const response = await getOrderDetail(currentId.value);
    const { data } = response;
    detailData.value = data;
    feedback.value = data.feedback || {};
  }catch{
    ElMessage.error("加载失败");
  }
};

</script>
<template>
  <div class="container">
    <div class="workorder-header">
     <div class="search-box">
        <el-select v-model="params.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
            <el-option label="待处理" :value="0"/>
            <el-option label="处理中" :value="1"/>
            <el-option label="已处理" :value="2"/>
            <el-option label="已结算" :value="3"/>
            <el-option label="已挂账" :value="6"/>
        </el-select>
        <el-date-picker  v-model="params.startDate" type="date"  placeholder=" 创建时间"  style="margin-left: 10px; width: 150px;"  value-format="YYYY-MM-DD HH:mm:ss"/>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
     </div>
    </div>
     <h1>工单列表</h1>
    <div class="table_container">
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 数据为空 -->
    <div v-else-if="workorderList.length === 0" class="empty">
      暂无数据
    </div>
    <div v-else>
    <el-table  :data="workorderList"  border  style="width: 900px; margin-top: 45px; " width="900px">
      <el-table-column label="id" prop="id"  min-width="80%" width="80%">
        <template #default="scope">
          <span class="title-link"  @click="isOpenDialog(scope.row.id)">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" min-width="80%" width="80%"/>
      <el-table-column label="姓名" prop="name" min-width="80%" width="80%"/>
      <el-table-column label="电话" prop="phone" min-width="80%" width="80%" />
      <el-table-column label="类型" prop="type" min-width="80%" width="80%">
        <template #default="scope">{{ orderTypeMap[scope.row.type] ?? '未知' }}</template>
      </el-table-column>
      <el-table-column label="状态" prop="status" >
        <template #default="scope">
            <el-tag type="warning" v-if="scope.row.status === 1 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="warning" v-if="scope.row.status === 2 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="success" v-if="scope.row.status === 3 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="success" v-if="scope.row.status === 5 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="success" v-if="scope.row.status === 6 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="error" v-if="scope.row.status === 0 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="error" v-if="scope.row.status === 7 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
            <el-tag type="danger" v-if="scope.row.status === 4 " >{{ statusMap[scope.row.status] ?? '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="address" min-width="95%" width="95%" />
      <el-table-column label="操作" min-width="100%">
        <template #default="scope">
          <div class="btn">
            <el-button @click="openDialog(scope.row)" :disabled="scope.row.status !== 0">编辑</el-button>
            <el-button type="danger" @click="deleteWorkorder(scope.row)" :disabled="scope.row.status !== 0">删除</el-button>
            <el-button type="primary"  v-if="scope.row.status === 0"  @click="assignDialogOpen(scope.row.id)">分配</el-button>
            <el-button type="success"   @click="archived(scope.row)"  v-if="scope.row.status === 3" >归档</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <div class="pagination-container" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-sizes="pageSize"
        page-size=10
        :page-sizes="[4, 5, 10, 15]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditDialogOpen" title="编辑工单" >
      <el-form :model="currentWorkorder" label-width="150px" style="width: 600px">
        <el-form-item label="工单ID"  >
          <el-input v-model="currentWorkorder.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="工单标题"  >
          <el-input v-model="currentWorkorder.title"></el-input>
        </el-form-item>
        <el-form-item label="工单描述">
          <el-input v-model="currentWorkorder.des" type="text"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="currentWorkorder.name" type="text"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="currentWorkorder.phone" type="text"></el-input>
        </el-form-item>
         <el-form-item label="地址">
      <!-- 导入地图选点组件 -->
          <MapSelector v-model="currentWorkorder.address">
        <!-- 通过插槽传入地址输入框 -->
            <template #address-input>
              <el-input v-model="currentWorkorder.address" placeholder="请输入地址或通过地图选择"/>
            </template>
          </MapSelector>
    </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentWorkorder.status" >
            <el-option label="待处理" :value="0"/>
            <el-option label="处理中" :value="1"/>
            <el-option label="已处理" :value="2"/>
            <el-option label="已结算" :value="3"/>
            <el-option label="待审核" :value="4"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveWorkorder">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog  v-model="assignDialog"  title="选择接单员分配"  width="90%"  :close-on-click-modal="false" :fullscreen="false" >
      <div class="assign-card-container">
        <!-- 4. 循环渲染接单员卡片：假设 delivererList 是接单员数据数组 -->
        <el-card   v-for="(deliverer, index) in delivererList" :key="deliverer.id" class="assign-card">
          <!-- 卡片内容：接单员信息 -->
          <div class="card-content">
            <!-- 姓名 -->
            <div class="info-item">
              <span class="label">员工姓名：</span>
              <span class="value">{{ deliverer.employeeName }}</span>
            </div>
            <!-- 单量 -->
            <div class="info-item">
              <span class="label">等级 </span>
              <span class="value">{{ deliverer.level }} </span>
            </div>
            <div class="info-item">
              <span class="label">当月工单 </span>
              <span class="value">{{ deliverer.monthOrderCount }} </span>
            </div>
            <div class="info-item">
              <span class="label">进行中</span>
              <span class="value">{{ deliverer.currentOrderCount}} </span>
            </div>
            <!-- 星级：用 Element Plus 的星星组件 -->
            <div class="info-item">
              <span class="label">服务星级：</span>
              <el-rate v-model="deliverer.starLevel" disabled  size="small" ></el-rate>
            </div>
            <!-- 标签：用标签组件展示（如“高效”“优质”） -->
            <div class="info-item tags">
              <span class="label">标签：</span>
              <el-tag > {{ deliverer.tags}}  </el-tag>
            </div>
          </div>
          <!-- 5. 右下角的分配按钮：固定在卡片右下角 -->
          <div class="assign-btn-container">
            <el-button  type="primary"  size="small"  @click="handleAssign(deliverer)"  >  分配  </el-button>
          </div>
        </el-card>
      </div>
    </el-dialog>
    <el-dialog  v-model="dialogVisible"  title="工单详情" width="50%"  :before-close="handleClose"  custom-class="workorder-detail-dialog" >
      <el-form :model="detailData" label-width="120px" class="detail-form">
        <el-form-item label="ID">{{ detailData.id }}</el-form-item>
        <el-form-item label="标题">{{ detailData.title }}</el-form-item>
        <el-form-item label="描述">{{ detailData.des }}</el-form-item>
        <el-form-item label="姓名">{{ detailData.name }}</el-form-item>
        <el-form-item label="手机号">{{ detailData.phone }}</el-form-item>
        <el-form-item label="地址">{{ detailData.address }}</el-form-item>
        <el-form-item label="状态">
          <el-tag size="small"   :type="detailData.status === 3 ? 'success' : detailData.status === 2 ? 'warning' : detailData.status === 1 ? 'info' : 'default'"   >
            {{ detailData.statusDesc }}
          </el-tag>
        </el-form-item>
        <el-form-item label="星级">
          <el-rate v-model="feedback.rating" text-color="#ff9900" score-template="{value}" disabled />
        </el-form-item>
        <el-form-item label="评价">{{ feedback.comment || '暂无评价' }}</el-form-item>
        <el-form-item label="创建时间">{{ detailData.createTime }}</el-form-item>
        <el-form-item label="更改时间">{{ detailData.updateTime }}</el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible=false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.container {
  padding: 20px;
  background-color: white;
  min-height: 100vh; /* 使用100vh确保占满视口高度，100%可能因父元素高度问题无效 */
  width: 100%;
  display: flex; /* 开启Flex布局 */
  flex-direction: column; /* 子元素垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: flex-start; /* 垂直从顶部开始排列，可根据需要调整 */
}
.workorder-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 15px;
  padding-right: 15px; /* 右侧留与左侧相同的间距 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
  margin-bottom: 15px; /* 与下方表格保持距离 */
}
.search-box {
  padding-left: 15px;
  display: flex; /* 使用Flex布局使输入框和按钮横向排列 */
  align-items: center; /* 垂直居中对齐 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
}
.btn{
  display: flex;
  gap: 2px;
}
/* 表格容器 */
.table_container {
  background-color: white;
  height: 300px;
  width:900px; /* 宽度与搜索框一致 */
  margin-left: 40px;
  margin-top: 20px;
  box-sizing: border-box; /* 避免边框/内边距影响宽度 */
  align-items: center;
}
.title-link {
  color: #409eff; /* 蓝色，模拟链接样式 */
  cursor: pointer;
  text-decoration: underline; /* 下划线，增强可点击提示 */
}
.addBtn{
  margin-right: 160px;
}
.pagination-container {
  padding: 10px 0;
  align-items: center;
}
.assign-card-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 每行4个等宽列 */
  gap: 20px; /* 卡片之间的间距 */
  padding: 10px 0;
  min-height: 300px;
}

/* 单个卡片样式 */
.assign-card {
  width: 100%; /* 宽度自适应网格列 */
  height: 240px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
  border-radius: 4px;
  position: relative;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  background-color: #fff;
 }
.assign-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  transform: translateY(-3px);
 }

 /* 卡片内容区域 */
 .card-content {
  padding: 15px;
  height: calc(100% - 80px); /* 为按钮留出空间 */
  }

  .info-item {
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中对齐 */
  width: 100%; /* 占满卡片宽度 */
  margin-bottom: 10px; /* 项与项之间的间距 */
  text-align: left; /* 文本左对齐 */
}

/* 标签样式 - 固定宽度确保对齐 */
.info-item .label {
  width: 80px; /* 固定标签宽度，让内容对齐更整齐 */
  font-weight: 500; /* 标签稍粗 */
  margin-right: 10px; /* 标签与内容之间的间距 */
  flex-shrink: 0; /* 防止标签被压缩 */
}

/* 内容样式 - 左对齐并填充剩余空间 */
.info-item .value {
  flex-grow: 1; /* 填充剩余空间 */
  text-align: left; /* 强制左对齐 */
  word-break: break-all; /* 内容过长时自动换行 */
}

        /* 标签容器 */
 .tags {
 flex-wrap: wrap;
  display: flex;
  align-items: flex-start;
 }

        .tags .el-tag {
            margin-right: 5px;
            margin-bottom: 5px;
        }

        /* 防止标签内容换行 */
        .no-wrap-tag {
            white-space: nowrap;
        }

        /* 分配按钮容器 */
        .assign-btn-container {
            position: absolute;
            bottom: 15px;
            right: 15px;
        }

        /* 无数据提示 */
        .no-data {
            grid-column: 1 / span 4;
            text-align: center;
            padding: 50px 0;
            color: #909399;
            font-size: 14px;
        }

        /* 响应式设计：在小屏幕上调整为每行2个卡片 */
        @media (max-width: 1200px) {
            .assign-card-container {
                grid-template-columns: repeat(3, 1fr);
            }
            .no-data {
                grid-column: 1 / span 3;
            }
        }

        @media (max-width: 900px) {
            .assign-card-container {
                grid-template-columns: repeat(2, 1fr);
            }
            .no-data {
                grid-column: 1 / span 2;
            }
        }

        @media (max-width: 600px) {
            .assign-card-container {
                grid-template-columns: 1fr;
            }
            .no-data {
                grid-column: 1;
            }
        }

        /* 自定义标题样式 */
        .dialog-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
            padding-bottom: 15px;
            border-bottom: 1px solid #e6e6e6;
            margin-bottom: 20px;
        }

</style>
